package com.qf.qfzuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.pojo.R;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return -5;
    }

    /**
     * 判断是否要执行过滤业务（run方法中的业务）
     * 返回false，不执行
     * 返回true，执行
     * @return
     */
    @Override
    public boolean shouldFilter() {

        //登录相关&注册相关 不需要拦截--false
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();

        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")){
            return false;
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //判断是否登录，从头或者请求参数中获取token信息--对token验证
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();

        String token = request.getParameter("token");

        //对token做验证
        if (token != null && token.length() != 0){
            //校验 todo：进行jwt的验证

        }else{
            response.setContentType("application/json;charset=utf-8");
            //不合法 - 没登陆
            //表示停止向下路由
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            //提示用户为登录
            R r = R.error().putMsg("尚未登录");

            try {
                response.getWriter().write(JSON.toJSONString(r));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //这个返回值目前没有意义
        return null;
    }
}
